
#include <arpa/inet.h>
#include "Conexion.h"
#include <string>
#include <iostream>

using std::string;
using std::cout;
using std::endl;

Conexion::Conexion(int sd, struct sockaddr_in* address) : m_sd(sd){
    char ip[50];
    inet_ntop(PF_INET, (struct in_addr*)&(address->sin_addr.s_addr), ip,
    														sizeof(ip)-1);
    m_peerIP = ip;
    m_peerPort = ntohs(address->sin_port);
}

Conexion::~Conexion(){
    close(m_sd);
}


ssize_t Conexion::send(const string& datos){
	uint32_t size = htonl(datos.size());
	write(m_sd, &size, 4);
    return write(m_sd, datos.c_str(), datos.size());
}

string Conexion::receive(){
//	int len;
	string datos = "";
	uint32_t size = 0;
	char buffer[100000] = {};
//	len = sizeof(buffer);
	read(m_sd, &size, 4);
	size = ntohl(size);
	while (datos.size() < size){
		read(m_sd, buffer, size - datos.size());
		datos += buffer;
	}
    return datos;
}

string Conexion::getPeerIP(){
    return m_peerIP;
}

int Conexion::getPeerPort(){
    return m_peerPort;
}

